package org.example.sosi.apitestplatform.controller;

import org.example.sosi.apitestplatform.model.ApiTest;
import org.example.sosi.apitestplatform.respository.ApiTestRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@CrossOrigin(origins = "*")
@RestController
@RequestMapping("/api/tests")
public class ApiTestController {

    @Autowired
    private ApiTestRepository apiTestRepository;

    @GetMapping
    public List<ApiTest> getAllTests() {
        return apiTestRepository.findAll();
    }
    @CrossOrigin
    @GetMapping("/{id}")
    public ResponseEntity<ApiTest> getTestById(@PathVariable Long id) {
        Optional<ApiTest> test = apiTestRepository.findById(id);
        if (test.isPresent()) {
            System.out.println("Fetched API Test:"+test.get());
            return ResponseEntity.ok(test.get());
        }else{
            System.out.println("API Test not found for ID:"+id);
            return ResponseEntity.notFound().build();
        }

    }
    @CrossOrigin
    @PostMapping
    public ApiTest createTest(@RequestBody ApiTest apiTest) {
        return apiTestRepository.save(apiTest);
    }
    @CrossOrigin
    @PutMapping("/{id}")
    public ResponseEntity<ApiTest> updateTest(@PathVariable Long id, @RequestBody ApiTest apiTestDetails) {
        Optional<ApiTest> optionalTest = apiTestRepository.findById(id);
        if (optionalTest.isPresent()) {
            ApiTest apiTest = optionalTest.get();
            apiTest.setName(apiTestDetails.getName());
            apiTest.setEndpoint(apiTestDetails.getEndpoint());
            apiTest.setRequestType(apiTestDetails.getRequestType());
            apiTest.setRequestBody(apiTestDetails.getRequestBody());
            return ResponseEntity.ok(apiTestRepository.save(apiTest));
        } else {
            return ResponseEntity.notFound().build();
        }
    }
    @CrossOrigin
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteTest(@PathVariable Long id) {
        Optional<ApiTest> test = apiTestRepository.findById(id);
        if (test.isPresent()) {
            apiTestRepository.deleteById(id);
            return ResponseEntity.noContent().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
